//
//  HNSH_RefundApplyViewController.m
//  HNSH_SingleProject
//
//  Created by 李宇廷 on 2023/3/1.
//

#import "HNSH_RefundApplyViewController.h"

//view
#import "HNSH_ApplyRefundHeader.h"
#import "HNSH_ApplyRefundTypeCell.h"
#import "HNSH_ApplyRefundContentCell.h"
#import "HNSH_ApplyRefundImageCell.h"
#import "HNSH_ApplyRefundContactCell.h"
#import "HNSH_ApplyRefundFooter.h"
#import "CGXStringPickerView.h"

static NSString * headerViewString = @"HNSH_ApplyRefundHeaderView";
static NSString * firstCellString = @"HNSH_ApplyRefundTypeCell";
static NSString * secondCellString = @"HNSH_ApplyRefundContentCell";
static NSString * thirdCellString = @"HNSH_ApplyRefundImageCell";
static NSString * fourthCellString = @"HNSH_ApplyRefundContactCell";
static NSString * footerViewString = @"HNSH_ApplyRefundFooterView";

@interface HNSH_RefundApplyViewController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, strong)UIImagePickerController * imagePicker;

/* dataArray */
@property (nonatomic, strong) NSArray *dataArray;

/* typesArray */
@property (nonatomic, strong) NSArray *typesArray;

/* isRefund */
@property (nonatomic, assign) BOOL isRefund;
/**  */
@property (nonatomic, copy)NSString * type;
/**  */
@property (nonatomic, copy)NSString * reason;
/**  */
@property (nonatomic, copy)NSString * des;
/**  */
@property (nonatomic, copy)NSString * name;
/**  */
@property (nonatomic, copy)NSString * phone;
/**  */
@property (nonatomic, strong)NSMutableArray * imgsArray;

/* account_type 0 无现金退款 可以不传 1：支付宝 2：银行卡*/
@property (nonatomic, assign) NSInteger account_type;
/* 账号姓名 */
@property (nonatomic, copy) NSString *account_name;
/* 账号 */
@property (nonatomic, copy) NSString *account;
/* 银行卡开户行 */
@property (nonatomic, copy) NSString *additional;

/* show_account */
@property (nonatomic, assign) BOOL show_account;
/* account_list */
@property (nonatomic, strong) NSArray *account_list;

/* footerView */
@property (nonatomic, strong) HNSH_ApplyRefundFooter *footerView;

@end

@implementation HNSH_RefundApplyViewController

//MARK: Cycle Methods
- (void)viewDidLoad{
    [super viewDidLoad];
    
    [self showNavTitle:@"申请退货" showLeftItem:YES];
    self.view.backgroundColor = [UIColor appBGColor];
        
    [self setDefaultData];
    
    [self loadConfigData];
    
    [self configCollectionView];
}

//MARK: Myself Methods
- (void)addAllViews{
    [self.view addSubview:self.collectionView];
}

- (void)setDefaultData{
    self.dataArray = @[
        @{@"title":@"退款类型*", @"place":@"请选择退款类型", @"content":self.type ? : @"", @"isRefund":@(self.isRefund)},
        @{@"title":@"退货原因*", @"place":@"请选择退货原因", @"content":self.reason ? : @""},
        @{@"title":@"问题描述*", @"place":@"请输入退货的问题描述", @"content":self.des ? : @""},
        @{@"title":@"上传凭证（最多6张）", @"place":@"", @"content":@""},
        @{@"title":@"联系人", @"place":@"联系人：", @"content":self.name ? : @""},
        @{@"title":@"联系电话", @"place":@"联系电话：", @"content":self.phone ? : @""},
    ];
    [self.collectionView reloadData];
}

//MARK: 获取退款类型和原因
- (void)loadConfigData{
    [HNSH_ShopNetServer requestGoodsOrderAfterSalesTypeWithOrderId:self.orderId success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            NSArray * list = responseObject.resultset[@"after_sales_type_list"];
            self.typesArray = list;
            
            self.show_account = [responseObject.resultset[@"show_account"] boolValue];
            self.account_list = responseObject.resultset[@"account_list"];
            [self.footerView configAccount:self.show_account account_list:self.account_list];
        }
    } Failure:^(NSError * _Nullable error) {
            
    }];
}

- (void)loadRefundData{
//    [CFBNetworkHelper postDataWithPathUrl:URL_Goods_RefundType params:nil from:NO needToken:YES successBlock:^(BOOL result, NSString * _Nonnull message, NSDictionary * _Nonnull dic) {
//        if (result) {
//            NSArray * list = dic[@"data"];
//            self.typesArray = list;
//        } else {
//            [MBProgressHUD showText:message];
//        }
//    } failBlock:^(NSError * _Nonnull error) {
//        [MBProgressHUD showText:error.localizedDescription];
//    }];
}

- (void)showImageSheet{
    [self.view endEditing:YES];
    UIAlertController * cameraAlert = [UIAlertController alertControllerWithTitle:@"请选择" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction * camera = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self showCamera];
    }];
    UIAlertAction * photo = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        // 打开相册
        [self showPhotosAlbum];
    }];
    UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [cameraAlert addAction:camera];
    [cameraAlert addAction:photo];
    [cameraAlert addAction:cancel];
    [self presentViewController:cameraAlert animated:YES completion:nil];
}

/** 拍照 */
- (void)showCamera{
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
        UIAlertController * a = [UIAlertController alertControllerWithTitle:@"提示" message:@"无相机设备" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        [a addAction:cancel];
        [self presentViewController:a animated:YES completion:nil];
        return;
    }
    self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    self.imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    [self presentViewController:self.imagePicker animated:YES completion:nil];
}

/** 相册选择 */
- (void)showPhotosAlbum{
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
        UIAlertController * a = [UIAlertController alertControllerWithTitle:@"提示" message:@"设备无相册" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        [a addAction:cancel];
        [self presentViewController:a animated:YES completion:nil];
        return;
    }
    self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    self.imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    [self presentViewController:self.imagePicker animated:YES completion:nil];
}

//MARK: 提交
- (void)commit{
    if (!self.type.length) {
        [self.view makeToast:@"请选择退款类型"];
        return;
    }
    if (!self.reason.length) {
        [self.view makeToast:@"请选择退款原因"];
        return;
    }
    if (!self.des.length) {
        [self.view makeToast:@"请输入问题描述"];
        return;
    }
    if (!self.name.length) {
        [self.view makeToast:@"请输入联系人"];
        return;
    }
    if (!self.phone.length) {
        [self.view makeToast:@"请输入联系电话"];
        return;
    }
    if (self.imgsArray.count) {
        [self uploadImages];
    } else {
        [self commitWithImages:nil];
    }
}

- (void)uploadImages{
    [kSTWindow makeToastActivity];
    [DLUploadImageTool uploadImages:self.imgsArray progress:^(CGFloat percent) {
        
    } success:^(id responseObject) {
        [kSTWindow hideAllToasts];
        [self commitWithImages:responseObject];
    } failure:^(NSError *error) {
        [kSTWindow hideAllToasts];
    }];
}

- (void)commitWithImages:(NSArray *)imgsArray{
    NSMutableDictionary * params = [NSMutableDictionary dictionaryWithDictionary:@{@"order_id":self.orderId, @"refund_type":self.isRefund ? @0 : @1, @"refund_reason":self.reason, @"refund_desc":self.des, @"contact_name":self.name, @"contact_phone":self.phone}];
    if (imgsArray.count) {
        [params setValue:imgsArray forKey:@"voucher_urls"];
    }
    if (self.account_type > 0) {
        [params setValue:@(self.account_type) forKey:@"account_type"];
        [params setValue:self.account_name forKey:@"name"];
        [params setValue:self.account forKey:@"account"];
        if (self.account_type == 2) {
            [params setValue:self.additional forKey:@"additional"];
        }
    }
    [HNSH_ShopNetServer requestGoodsOrderAfterSalesApplyWithParams:params success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            [kSTWindow makeToast:@"申请成功"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"KOrderListRefrash" object:nil];
            [self.navigationController popViewControllerAnimated:YES];
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

//MARK: Getter Methods
- (UIImagePickerController *)imagePicker{
    if (!_imagePicker) {
        _imagePicker = [[UIImagePickerController alloc] init];
        _imagePicker.delegate = self;
        _imagePicker.allowsEditing = YES;
    }
    return _imagePicker;
}

- (NSMutableArray *)imgsArray{
    if (!_imgsArray) {
        _imgsArray = [@[] mutableCopy];
    }
    return _imgsArray;
}

//MARK: UIImagePickerControllerDelegate Methods
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    [picker dismissViewControllerAnimated:YES completion:^{
        NSData * data = UIImageJPEGRepresentation([info objectForKey:UIImagePickerControllerEditedImage], 0.5);
        UIImage * img = [UIImage imageWithData:data];
        [self.imgsArray addObject:img];
        [self.collectionView reloadData];
    }];
}

- (void)configCollectionView {
    self.collectionView.backgroundColor = [UIColor appBGColor];
    [self.collectionView registerClass:[HNSH_ApplyRefundHeader class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerViewString];
    [self.collectionView registerClass:[HNSH_ApplyRefundTypeCell class] forCellWithReuseIdentifier:firstCellString];
    [self.collectionView registerClass:[HNSH_ApplyRefundContentCell class] forCellWithReuseIdentifier:secondCellString];
    [self.collectionView registerClass:[HNSH_ApplyRefundImageCell class] forCellWithReuseIdentifier:thirdCellString];
    [self.collectionView registerClass:[HNSH_ApplyRefundContactCell class] forCellWithReuseIdentifier:fourthCellString];
    [self.collectionView registerClass:[HNSH_ApplyRefundFooter class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:footerViewString];
}

#pragma mark - UICollectionViewDelegate Methods
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 6;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (section == 3) {
        return self.imgsArray.count + 1;
    }
    return 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary * dic = self.dataArray[indexPath.section];
    if (indexPath.section == 0 || indexPath.section == 1) {
        HNSH_ApplyRefundTypeCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:firstCellString forIndexPath:indexPath];
        cell.dic = dic;
        if (indexPath.section == 0) {
            cell.placeholder = @"请选择退货类型";
        } else {
            cell.placeholder = @"请选择退货原因";
        }
        return cell;
    } else if (indexPath.section == 2) {
        HNSH_ApplyRefundContentCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:secondCellString forIndexPath:indexPath];
        cell.dic = dic;
        
        WeakSelf(weakSelf);
        cell.changeBlock = ^(NSString * _Nonnull des) {
            weakSelf.des = des;
        };
        return cell;
    } else if (indexPath.section == 3) {
        HNSH_ApplyRefundImageCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:thirdCellString forIndexPath:indexPath];
        if (indexPath.row == self.imgsArray.count) {
            cell.image = nil;
        } else {
            cell.image = self.imgsArray[indexPath.row];
        }
        WeakSelf(weakSelf);
        cell.deletePhotoBlock = ^(HNSH_ApplyRefundImageCell *selCell) {
            NSIndexPath * index = [weakSelf.collectionView indexPathForCell:selCell];
            [weakSelf.imgsArray removeObjectAtIndex:index.row];
            [weakSelf.collectionView reloadData];
        };
        return cell;
    } else {
        HNSH_ApplyRefundContactCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:fourthCellString forIndexPath:indexPath];
        cell.dic = dic;
        
        WeakSelf(weakSelf);
        cell.fieldChangeBlock = ^(HNSH_ApplyRefundContactCell * _Nonnull selCell, NSString * _Nonnull content) {
            NSIndexPath * index = [weakSelf.collectionView indexPathForCell:selCell];
            if (index.section == 4) {
                weakSelf.name = content;
            }
            if (index.section == 5) {
                weakSelf.phone = content;
            }
        };
        return cell;
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0 || indexPath.section == 1) {
        return CGSizeMake(kScreenWidth, 50);
    } else if (indexPath.section == 2) {
        return CGSizeMake(kScreenWidth, 160);
    } else if (indexPath.section == 3) {
        return CGSizeMake(80, 80);
    } else {
        return CGSizeMake(kScreenWidth, 50);
    }
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 16, 0, 16);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 16;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    NSDictionary * dic = self.dataArray[indexPath.section];
    if (kind == UICollectionElementKindSectionHeader) {
        HNSH_ApplyRefundHeader * view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerViewString forIndexPath:indexPath];
        view.dic = dic;
        return view;
    } else {
        if (indexPath.section == 5) {
            HNSH_ApplyRefundFooter * view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:footerViewString forIndexPath:indexPath];
            self.footerView = view;
            view.isRefund = self.isRefund;
            WeakSelf(weakSelf);
            view.commitFeedbackBlock = ^(NSInteger account_type, NSString * _Nonnull name, NSString * _Nonnull account, NSString * _Nonnull additional) {
                weakSelf.account_type = account_type;
                weakSelf.account_name = name;
                weakSelf.account = account;
                weakSelf.additional = additional;
                [weakSelf commit];
            };
            return view;
        }
    }
    return nil;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(collectionView.frame.size.width, 46);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    if (section == 5) {
        return CGSizeMake(collectionView.frame.size.width, 500);
    }
    return CGSizeZero;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        [self chooseType];
    }
    if (indexPath.section == 1) {
        [self chooseReason];
    }
    if (indexPath.section == 3) {
        [self showImageSheet];
    }
}

- (void)chooseType{
    [self.view endEditing:YES];
    //
    if (self.isRefund) {
        //申请退款的状态是固定的 不可选
        return;
    }
    NSArray * array = [self getTypesArray];
    if (!array || !array.count) {
        [self loadConfigData];
        [self.view makeToast:@"请选择退款类型"];
        return;
    }
    CGXPickerViewManager *manager = [[CGXPickerViewManager alloc]init];
    manager.leftBtnBGColor = [UIColor appGreenColor];
    manager.rightBtnBGColor = [UIColor appGreenColor];
    manager.titleLabelColor = [UIColor appGreenColor];
    manager.leftBtnborderColor = [UIColor appGreenColor];
    manager.rightBtnborderColor = [UIColor appGreenColor];
    [CGXStringPickerView showStringPickerWithTitle:@"退款类型" DataSource:array DefaultSelValue:nil IsAutoSelect:NO Manager:manager ResultBlock:^(id selectValue, id selectRow) {
        self.type = selectValue;
        [self setDefaultData];
    }];
}

- (void)chooseReason{
    [self.view endEditing:YES];
    //
    if (!self.type.length) {
        [self.view makeToast:@"请选择退款类型"];
        return;
    }
    NSArray * array = [self getArrayWithKey:self.type];
    if (!array || !array.count) {
        [self loadConfigData];
        [self.view makeToast:@"请选择退款原因"];
        return;
    }
    CGXPickerViewManager *manager = [[CGXPickerViewManager alloc]init];
    manager.leftBtnBGColor = [UIColor appGreenColor];
    manager.rightBtnBGColor = [UIColor appGreenColor];
    manager.titleLabelColor = [UIColor appGreenColor];
    manager.leftBtnborderColor = [UIColor appGreenColor];
    manager.rightBtnborderColor = [UIColor appGreenColor];
    [CGXStringPickerView showStringPickerWithTitle:@"退款原因" DataSource:array DefaultSelValue:nil IsAutoSelect:YES Manager:manager ResultBlock:^(id selectValue, id selectRow) {
        self.reason = selectValue;
        [self setDefaultData];
    }];
}

- (NSArray *)getTypesArray{
    NSMutableArray * arr = [NSMutableArray new];
    for (NSDictionary * dic in self.typesArray) {
        NSString * refundName = dic[@"name"];
        [arr addObject:refundName];
    }
    return arr.copy;
}

- (NSArray *)getArrayWithKey:(NSString *)key{
    NSArray * list = nil;
    for (NSDictionary * dic in self.typesArray) {
        NSString * refundName = dic[@"name"];
        if ([refundName isEqualToString:key]) {
            list = dic[@"reasons"];
        }
    }
    NSMutableArray * arr = [NSMutableArray new];
    for (NSDictionary * dic in list) {
        NSString * refundName = dic[@"name"];
        [arr addObject:refundName];
    }
    if (arr.count) {
        return arr.copy;
    }
    return nil;
}

@end
